package demo.mianshi.thread;

public class _交替打印 {
    static volatile boolean flag = false;

    public static void main(String[] args) {
        // 两个线程交替打印a,b,共打印100次
        Object lock = new Object();
        new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 100; i++) {
                    while (flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("a");
                    flag = true;
                    lock.notify();
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 100; i++) {
                    while (!flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("b");
                    flag = false;
                    lock.notify();
                }
            }
        }).start();
    }
}
